package com.api.phm.domain.query.alarmRule;

import io.netty.util.internal.StringUtil;
import lombok.Getter;
import lombok.Setter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;

/**
 * 告警校验
 */
@Getter
@Setter
public class AlarmRuleCheck {
    /**
     * children内链接属性；and 则全判断，or 为或
     */
    private String logic;
    /**
     * 设备信息编号
     */
    private String device;
    /**
     * sum: 汇总总量
     * count: 统计总数
     * max: 最大值
     * min: 最小值
     * avg: 平均值
     * vare: 方差
     * last: 最新值
     */
    private String aggr;
    /**
     * 判定类型
     * gte：大于等于
     * gt：大于
     * eq：等于
     * neq：不等于
     * lt：小于
     * lte：小于等于
     * lk：存在文字
     * nk：不存在
     */
    private String operator;
    /**
     * 判读值
     */
    private String contrast;
    /**
     * 分钟数
     */
    private int times;
    /**
     * 子规则
     */
    private List<AlarmRuleCheck> children;
    /**
     * BiFunction< 实际值， 目标值（设定），返回类型>
     */
    private static final Map<String, BiFunction<Double, Double, Boolean>> operatorDoubMap = new HashMap<>();
    /**
     * BiFunction< 实际值， 目标值（设定），返回类型>
     */
    private static final Map<String, BiFunction<String, String, Boolean>> operatorStrMap = new HashMap<>();

    static {
        operatorDoubMap.put("gt", (a, b) -> a > b);
        operatorDoubMap.put("gte", (a, b) -> a >= (b)); // 非相等，即 >= 变成 !=
        operatorDoubMap.put("lt", (a, b) -> a < b);
        operatorDoubMap.put("lte", (a, b) -> a <= b);
        operatorDoubMap.put("eq", Double::equals);
        operatorDoubMap.put("neq", (a, b) -> !a.equals(b));
        operatorStrMap.put("lk", String::contains);
        operatorStrMap.put("nk", (a, b) -> !a.contains(b));
    }

    /**
     * @param rule_type 告警类型 1：
     * @param operator  比较方法
     * @param param1    实际值
     * @param param2    警戒值
     * @return
     */
    public static Boolean check(int rule_type, String operator, String param1, String param2) {
        return false;
    }

    private Boolean judgeStr(String operator, String param1, String param2) {
        if (StringUtil.isNullOrEmpty(operator) || !operatorStrMap.containsKey(operator)) return false;
        BiFunction<String, String, Boolean> operatorFun = operatorStrMap.get(operator);
        return operatorFun.apply(param1, param2);
    }

    private static Boolean judgeDouble(String operator, Double param1, Double param2) {
        if (StringUtil.isNullOrEmpty(operator) || !operatorDoubMap.containsKey(operator)) return false;
        BiFunction<Double, Double, Boolean> operatorFun = operatorDoubMap.get(operator);
        return operatorFun.apply(param1, param2);
    }
}
